package cn.mw.controller;

import cn.mw.domain.Device;
import cn.mw.service.IDeviceService;
import cn.mw.util.JSONResult;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceController {
    @Autowired
    private IDeviceService deviceService;
    @PostMapping("/add")
    public JSONResult add(@RequestBody Device device){
        try {
            deviceService.add(device);
            return JSONResult.success("操作成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JSONResult.success("操作失败");
        }
    }
    @GetMapping("/getDeviceInfoById/{id}")
    @SentinelResource(value="Device-server-getDeviceInfoById", blockHandler = "degradationMethod",fallback = "fuseDegradation")
    public JSONResult getDeviceInfoById(@PathVariable("id") Long id){
        try {
            return JSONResult.success(deviceService.getDeviceInfoById(id));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JSONResult.success("操作失败");
        }
    }
    public JSONResult degradationMethod(@PathVariable("id") Long id,BlockException e){
        e.printStackTrace();
        return JSONResult.error("流控了");
    }
    public JSONResult fuseDegradation(@PathVariable("id") Long id,Throwable e){
        e.printStackTrace();
        return JSONResult.error("熔断了");
    }


    /**
     * 查询楼层内所有设备
     * @param floorId
     * @return
     */
    @GetMapping("/getDevice/{floorId}")
    public List<Device> getDevice(@PathVariable("floorId") String floorId){
        return  deviceService.getDevice(floorId);
    }

}
